﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SinsenMVC.Helpers;
using SinsenWeb.Helpers;
using SinsenWeb.Helpers.ActionFilters;
using SinsenWeb.Models;
using SinsenWeb.Models.ViewDataTypes;

namespace SinsenWeb.Controllers
{
    public class MembersController:BaseController
    {
        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        public ActionResult List()
        {
            var members = Member.FindAllActive();
            ViewData.Model = members;
            return View();
        }

        [LoggedIn]
        public ActionResult Show(int id)
        {
            var member = Member.Find(id);
            ViewData.Model = member;
            return View();
        }


        [LoggedIn]
        public ActionResult Edit(int id)
        {
            var member = Member.Find(id);

            if(Helper.CanEditMember(member))
            {
                var instruments = Instrument.FindAll();
                ViewData.Model = new EditMember{Member = member, Instruments = instruments};
                return View();
            }else
            {
                MessageHelper.Alert("Du kan ikke redigere andres profiler");
                return RedirectToAction("Show", new { member.Id });
            }
        }

        public ActionResult Update(int id)
        {
            var member = Member.Find(id);
            UpdateModel(member, "Member");
            DateTime temp;
            if (DateTime.TryParseExact(Request.Form["Member.BirthDate"], "dd/MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out temp))
            {
                member.BirthDate = temp;
            }else
            {
                member.BirthDate = null;
            }
            if (DateTime.TryParseExact(Request.Form["Member.StartedDate"], "dd/MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out temp))
            {
                member.StartedDate = temp;
            }
            else
            {
                member.StartedDate = null;
            }
            member.Instrument = Instrument.Get(Request.Form["Member.Instrument"]);

            var picFile = Request.Files["Member.Picture"];

            if(picFile!=null)
            {
                var picName = picFile.FileName;

            }

            member.SaveAndFlush();
            MessageHelper.Message("Endringer ble lagret");
            return RedirectToAction("Show",new{member.Id});
        }

    }
}
